<?php

namespace app\hotel\controller;

use think\Controller;

use function PHPSTORM_META\map;

class Order extends Controller
{
    public function _initialize()
    {
        // 继承父类
        parent::_initialize();
        $this->BusinessModel = model('Business.Business');
        $this->RoomModel = model('Hotel.Room');
        $this->CouponReceiveModel = model('Coupon.Receive');
        $this->GuestModel = model('Hotel.Guest');
        $this->OrderModel = model('Hotel.Order');
        $this->RecordModel = model('Business.Record');
    }

    // 酒店预定
    public function add()
    {
        if ($this->request->isPost())
        {
            $busid = $this->request->param('busid', 0, 'trim');
            $roomid = $this->request->param('roomid', 0, 'trim');
            $couponid = $this->request->param('couponid', null, 'trim');
            $guest = $this->request->param('guest', '', 'trim');
            $starttime = $this->request->param('starttime', 0, 'trim');
            $endtime = $this->request->param('endtime', 0, 'trim');
            $remark = $this->request->param('remark', '', 'trim');
            $type = $this->request->param('type', 'money', 'trim');

            $business = $this->BusinessModel->find($busid);

            if (!$business)
            {
                $this->error('用户不存在');
                exit;
            }

            $room = $this->RoomModel->find($roomid);

            if (!$room)
            {
                $this->error('酒店房间不存在');
                exit;
            }

            $guestlist = $this->GuestModel->select($guest);

            if (!$guestlist)
            {
                $this->error('入住客户不存在');
                exit;
            }

            //房间是否可以在预约
            $where = [
                'roomid' => $roomid,
                'status' => ['IN', '1,2']
            ];

            $count = $this->OrderModel->where($where)->count();

            $update =  bcsub($room['total'], $count);

            if ($update <= 0)
            {
                $this->error('该房型已全部预约');
                exit;
            }

            //查看优惠券是否过期
            $receive = $this->CouponReceiveModel->with('coupon')->find($couponid);

            if ($receive)
            {
                if ($receive['status'] == '0')
                {
                    $this->error('优惠券已过期');
                    exit;
                }
            }

            // 先计算天数 先计算出价格
            $day = intval(($endtime - $starttime) / 86400);
            // 计算价格
            $price = $origin_price = bcmul($room['price'], $day, 2);

            // 优惠价格
            if ($receive)
            {
                $rate = isset($receive['coupon']['rate']) ? $receive['coupon']['rate'] : 1;
                $price = bcmul($price, $rate, 2);
            }

            //判断是否是使用余额支付
            if ($type == 'money')
            {
                // 开启事务
                $this->OrderModel->startTrans();
                $this->BusinessModel->startTrans();
                $this->RecordModel->startTrans();
                $this->CouponReceiveModel->startTrans();

                // 订单表
                $OrderData = [
                    'busid' => $busid,
                    'roomid' => $roomid,
                    'guest' => $guest,
                    'origin_price' => $origin_price,
                    'price' => $price,
                    'starttime' => $starttime,
                    'endtime' => $endtime,
                    'status' => '1',
                    'couponid' => $couponid ? $couponid : null,
                    'remark' => $remark,
                    'type' => $type
                ];

                $OrderStatus = $this->OrderModel->save($OrderData);
                if($OrderStatus === false)
                {
                    $this->error($this->OrderModel->getError());
                    exit;
                }

                // 剩余余额
                $money = bcsub($business['money'], $price, 2);

                $BusinessData = [
                    'id' => $busid,
                    'money' => $money
                ];

                $validate = [
                    [
                        'money' => ['number', 'egt:0'],
                    ],
                    [
                        'money.number'  => '余额必须是数字类型',
                        'money.egt'      => '余额不足请先充值',
                    ]
                ];

                // 用户表
                $BusinessStatus = $this->BusinessModel->validate(...$validate)->isUpdate(true)->save($BusinessData);

                if ($BusinessStatus === false)
                {
                    $this->OrderModel->rollback();
                    $this->error($this->BusinessModel->getError());
                    exit;
                }

                $RecordData = [
                    'total' => $price,
                    'busid' => $busid,
                    'content' => "预定了酒店{$room['name']},{$day}天,花费了￥{$price}元",
                ];

                // 消费记录表
                $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);
                if ($RecordStatus === false)
                {
                    $this->OrderModel->rollback();
                    $this->BusinessModel->rollback();
                    $this->error($this->RecordModel->getError());
                    exit;
                }

                //如果有选择优惠券那么就要更新优惠券使用状态
                if ($receive)
                {
                    $CouponReceiveData = [
                        'id' => $couponid,
                        'status' => '0'
                    ];

                    $CouponReceiveStatus =  $this->CouponReceiveModel->isUpdate(true)->save($CouponReceiveData);
                    if ($CouponReceiveStatus === false)
                    {
                        $this->OrderModel->rollback();
                        $this->BusinessModel->rollback();
                        $this->RecordModel->rollback();
                        $this->error($this->CouponReceiveModel->getError());
                        exit;
                    }
                }

                if($OrderStatus === false || $BusinessStatus === false || $RecordStatus === false)
                {
                    $this->OrderModel->rollback();
                    $this->BusinessModel->rollback();
                    $this->RecordModel->rollback();
                    $this->CouponReceiveModel->rollback();
                    $this->error('预约失败');
                    exit;
                }
                else
                {
                    $this->OrderModel->commit();
                    $this->BusinessModel->commit();
                    $this->RecordModel->commit();
                    $this->CouponReceiveModel->commit();
                    $this->success('预约成功');
                }
            }
        }
    }
    
    // 列表
    public function index()
    {
        if($this->request->isPost())
        {
            $busid = $this->request->param('busid', 0, 'trim');
            $page = $this->request->param('page', 1, 'trim');
            $status = $this->request->param('status', 'all', 'trim');

            $business = $this->BusinessModel->find($busid);

            if (!$business)
            {
                $this->error('用户不存在');
                exit;
            }

            $where = ['busid' => $busid];

            if($status != 'all')
            {
                $where['status'] = $status;
            }

            $list = $this->OrderModel->with('room')->where($where)->order('id desc')->page("$page,10")->select();

            if ($list)
            {
                $this->success('', '', $list);
                exit;
            }
            else
            {
                $this->error('暂无数据');
                exit;
            }
        }
    }
    
    // 详情
    public function info()
    {
        if ($this->request->isPost())
        {
            $busid = $this->request->param('busid', 0, 'trim');
            $orderid = $this->request->param('orderid', 0, 'trim');

            $business = $this->BusinessModel->find($busid);

            if (!$business)
            {
                $this->error('用户不存在');
                exit;
            }

            $order = $this->OrderModel->with('room')->find($orderid);

            if (!$order)
            {
                $this->error('预约订单不存在');
                exit;
            }

            $guestlist = $this->GuestModel->select($order['guest']);

            $order['guestlist'] = $guestlist;

            $this->success('', '', $order);
        }
    }

    // 申请退款
    public function refund()
    {
        if($this->request->isPost())
        {
            $busid = $this->request->param('busid', 0, 'trim');
            $orderid = $this->request->param('orderid', 0, 'trim');

            $business = $this->BusinessModel->find($busid);

            if (!$business)
            {
                $this->error('用户不存在');
                exit;
            }

            $order = $this->OrderModel->find($orderid);

            if (!$order)
            {
                $this->error('预约订单不存在');
                exit;
            }

            $result = $this->OrderModel->where('id', $orderid)->update(['status' => '-1']);

            if ($result === false)
            {
                $this->error($this->OrderModel->getError());
                exit;
            }
            else
            {
                $this->success('申请成功，待商家审核');
            }
        }
    }

    // 评价
    public function rate()
    {
        if($this->request->isPost())
        {
            $busid = $this->request->param('busid', 0, 'trim');
            $orderid = $this->request->param('orderid', 0, 'trim');
            $rate = $this->request->param('rate', 0, 'trim');
            $comment = $this->request->param('comment', '', 'trim');

            $business = $this->BusinessModel->find($busid);

            if (!$business)
            {
                $this->error('用户不存在');
                exit;
            }

            $order = $this->OrderModel->find($orderid);

            if (!$order)
            {
                $this->error('预约订单不存在');
                exit;
            }

            $data = [
                'id' => $orderid,
                'rate' => $rate,
                'comment' => $comment,
                'status' => '4'
            ];

            $result = $this->OrderModel->isUpdate(true)->save($data);

            if ($result === false)
            {
                $this->error($this->OrderModel->getError());
                exit;
            }
            else
            {
                $this->success('评价成功');
            }
        }
    }
}
